package com.hex.liyue.mainmodule.activity;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.hex.liyue.R;
import com.hex.liyue.commonmodule.activity.BaseActivity;
import com.hex.liyue.commonmodule.adapter.PagerAdapter;
import com.hex.liyue.commonmodule.config.Constant;
import com.hex.liyue.commonmodule.manager.UserManager;
import com.hex.liyue.commonmodule.utils.L;
import com.hex.liyue.commonmodule.utils.SPUtil;
import com.hex.liyue.commonmodule.utils.StatusBarCompatUtils;
import com.hex.liyue.lookingdatemodule.activity.InSomeDetailsActivity;
import com.hex.liyue.mainmodule.fragment.FragmentHome;
import com.hex.liyue.messagemodule.activity.ChatActivity;
import com.hex.liyue.messagemodule.activity.SystemMessageActivity;
import com.hex.liyue.messagemodule.fragment.FragmentMessage;
import com.hex.liyue.nearmodule.fragment.FragmentNear;
import com.hex.liyue.storemodule.fragment.FragmentStore;
import com.hex.liyue.usermodule.activity.LoginAndRegistActivity;
import com.hex.liyue.usermodule.fragment.MeFragment;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.util.NetUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;


/**
 * 这是一个主界面
 */
public class MainActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    @Bind(R.id.vp_home)
    ViewPager vpHome;

    @Bind(R.id.iv_main_yueyue)
    ImageView ivMainYueyue;
    @Bind(R.id.iv_near)
    ImageView ivNear;
    @Bind(R.id.iv_main_store)
    ImageView ivMainStore;
    @Bind(R.id.iv_main_message)
    ImageView ivMainMessage;
    @Bind(R.id.iv_main_my)
    ImageView ivMainMy;

    @Bind(R.id.tv_message_unread_count)
    TextView tvMessageUnreadCount;

    private List<Fragment> list = new ArrayList<>();
    private FragmentMessage fragmentMessage;
    private MeFragment meFragment;
    private String appointment_id;

    @Override
    protected void bindPresenter() {

    }

    @TargetApi(Build.VERSION_CODES.DONUT)
    @Override
    protected void initData(Bundle extras) {
        Uri uri = getIntent().getData();
        if (uri != null) {
            appointment_id = uri.getQueryParameter("appointment_id");
        }
        if (!TextUtils.isEmpty(appointment_id)) {
            startInSomeDetailsActivity(appointment_id);
        }

        //注册一个监听连接状态的listener
        EMClient.getInstance().addConnectionListener(new MyConnectionListener());

        fragmentMessage = new FragmentMessage();
        meFragment = new MeFragment();
        list.add(new FragmentNear());
        list.add(new FragmentHome());
        list.add(new FragmentStore());
        list.add(fragmentMessage);
        list.add(meFragment);
        PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), list);
        vpHome.setAdapter(pagerAdapter);
        vpHome.setOffscreenPageLimit(4);
        vpHome.setOnPageChangeListener(this);
        fragmentMessage.setConversationListItemClickListener(new FragmentMessage.EaseConversationListItemClickListener() {
            @Override
            public void onListItemClicked(EMConversation conversation, int position) {
//                if (("admin").equals(conversation.getAllMessages().get(position).getFrom())) {
//                    conversation.getUserName();
//                    startActivity(new Intent(MainActivity.this, SystemMessageActivity.class));
//                } else {
                conversation.getAllMessages().size();
                if ("admin".equals(conversation.getUserName())) {
                    startActivity(new Intent(MainActivity.this, SystemMessageActivity.class));
                } else {
                    Intent intent = new Intent(MainActivity.this, ChatActivity.class);
//                    bundle.putString(Constant.EXTRA_USER_ID, conversation.getAllMessages().get(position).getStringAttribute("fromUid",""));
//                    bundle.putString("fromAvatar", conversation.getAllMessages().get(position).getStringAttribute("fromAvatar",""));
//                    bundle.putString("fromName", conversation.getAllMessages().get(position).getStringAttribute("fromName",""));
                    if (conversation.getAllMessages().get(position) != null) {
                        if (UserManager.getUserId().equals(conversation.getAllMessages().get(position).getStringAttribute("toUid", ""))) {
                            intent.putExtra("name", conversation.getAllMessages().get(position).getStringAttribute("fromName", ""));
                        } else if (UserManager.getUserId().equals(conversation.getAllMessages().get(position).getStringAttribute("fromUid", ""))) {
                            intent.putExtra("name", conversation.getAllMessages().get(position).getStringAttribute("toName", ""));
                        }
                    }
                    intent.putExtra("toUid", UserManager.getUserId());
                    intent.putExtra("toAvatar", UserManager.getUserAvator());
                    intent.putExtra("toName", UserManager.getNickName());
                    intent.putExtra(Constant.EXTRA_USER_ID, conversation.getUserName());
                    startActivity(intent);
//                    startActivity(new Intent(MainActivity.this, ChatActivity.class).putExtra(EaseConstant.EXTRA_USER_ID, conversation.getUserName()));
                }
//                }

            }
        });
    }

    /**
     * 打开约会详情界面
     *
     * @param appointment_id 约会id
     */
    private void startInSomeDetailsActivity(String appointment_id) {
        Intent intent = new Intent(this, InSomeDetailsActivity.class);
        intent.putExtra("appointment_id", appointment_id);
        startActivity(intent);
    }

    EMMessageListener messageListener = new EMMessageListener() {

        @Override
        public void onMessageReceived(List<EMMessage> messages) {
            // notify new message
//            for (EMMessage message : messages) {
//                MyNotification.show(MainActivity.this, "新消息", "收到了吗");
//                //EaseUI.getInstance().getNotifier().onNewMsg(message);
//            }
            refreshUIWithMessage();
        }

        @Override
        public void onCmdMessageReceived(List<EMMessage> messages) {
            for (EMMessage message : messages) {
                EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
                final String action = cmdMsgBody.action();//get the action user defined in command message
//                    if (action.equals(RedPacketConstant.REFRESH_GROUP_RED_PACKET_ACTION) && message.getChatType() == EMMessage.ChatType.GroupChat) {
//                        RedPacketUtil.receiveRedPacketAckMessage(message);
//                    }
            }
            refreshUIWithMessage();
        }

        @Override
        public void onMessageReadAckReceived(List<EMMessage> messages) {
        }

        @Override
        public void onMessageDeliveryAckReceived(List<EMMessage> message) {
        }

        @Override
        public void onMessageChanged(EMMessage message, Object change) {
        }
    };

    private void refreshUIWithMessage() {
        runOnUiThread(new Runnable() {
            public void run() {
                updateUnreadLabel();
                if (fragmentMessage != null) {
                    fragmentMessage.refresh();
                }
            }
        });
    }

    public void updateUnreadLabel() {
        int count = getUnreadMsgCountTotal();
        if (count > 0) {
            tvMessageUnreadCount.setText(String.valueOf(count));
            tvMessageUnreadCount.setVisibility(View.VISIBLE);
            SPUtil.getString(this, "msg", "msg");
        } else {
            tvMessageUnreadCount.setVisibility(View.INVISIBLE);
        }
    }

    public int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            L.d("WJ", "个人资料回来");
            meFragment.updateAvater();
        }
    }

    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
        }

        @Override
        public void onDisconnected(final int error) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    if (error == EMError.USER_REMOVED) {
                        // 显示帐号已经被移除
                    } else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
                        // 显示帐号在其他设备登录
                        showConflictDialog();
                        UserManager.setIsLogin(false);
                    } else {
                        if (NetUtils.hasNetwork(MainActivity.this)) {

                        }
                        //连接不到聊天服务器
                        else {

                        }
                        //当前网络不可用，请检查网络设置
                    }
                }
            });
        }
    }

    /**
     * 显示环信账号挤掉的对话框
     */
    public void showConflictDialog() {
        AlertDialog.Builder conflictBuilder = new AlertDialog.Builder(MainActivity.this);
        try {
            conflictBuilder.setTitle("提示");
            conflictBuilder.setMessage("你的账号已在其他地方登录");
            conflictBuilder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    startActivity(new Intent(MainActivity.this, LoginAndRegistActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));

                    finish();
                }
            });
            conflictBuilder.setCancelable(false);
            conflictBuilder.create().show();
        } catch (Exception e) {
            L.e("e", e.getMessage());
        }
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initToolbar() {
        StatusBarCompatUtils.compat(this);
    }

    @TargetApi(Build.VERSION_CODES.DONUT)
    @OnClick({R.id.ll_near, R.id.rl_main_yueyue, R.id.rl_main_store, R.id.rl_main_message, R.id.rl_main_my})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_near:
                vpHome.setCurrentItem(0, false);
                ivNear.setImageResource(R.drawable.near_select);
                break;
            case R.id.rl_main_yueyue:
                vpHome.setCurrentItem(1, false);
                ivMainYueyue.setImageResource(R.drawable.home_select);
                break;
            case R.id.rl_main_store:
                vpHome.setCurrentItem(2, false);
                ivMainStore.setImageResource(R.drawable.shop_select);
                break;
            case R.id.rl_main_message:
                vpHome.setCurrentItem(3, false);
                ivMainMessage.setImageResource(R.drawable.chat_select);
                break;
            case R.id.rl_main_my:
                vpHome.setCurrentItem(4, false);
                ivMainMy.setImageResource(R.drawable.mine_select);
                break;
        }
    }

    /**
     * 清楚按钮的所有的选中状态
     */
    public void clearAllCheckStatus() {
        //清除按钮
        ivNear.setImageResource(R.drawable.main_near_normal);
        ivMainYueyue.setImageResource(R.drawable.home_normal);
        ivMainStore.setImageResource(R.drawable.shop_normal);
        ivMainMessage.setImageResource(R.drawable.chat_normal);
        ivMainMy.setImageResource(R.drawable.mine_normal);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        clearAllCheckStatus();
        vpHome.setCurrentItem(position, false);
        switch (position) {
            case 0:
                ivNear.setImageResource(R.drawable.near_select);
                break;
            case 1:
                ivMainYueyue.setImageResource(R.drawable.home_select);
                break;
            case 2:
                ivMainStore.setImageResource(R.drawable.shop_select);
                break;
            case 3:
                ivMainMessage.setImageResource(R.drawable.chat_select);
                break;
            case 4:
                ivMainMy.setImageResource(R.drawable.mine_select);
                break;
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        EMClient.getInstance().chatManager().addMessageListener(messageListener);
//        if (!"".equals(SPUtil.getString(this, "mFlag", ""))) {
//            tvMessageUnreadCount.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
        tvMessageUnreadCount.setVisibility(View.GONE);
    }
}
